package com.tianye.salon.controller.admin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tianye.salon.controller.BaseController;
import com.tianye.salon.dao.AdminUserForAuthDto;
import com.tianye.salon.model.AdminModule;
import com.tianye.salon.model.AdminRole;
import com.tianye.salon.model.AdminUser;
import com.tianye.salon.service.AdminModuleService;
import com.tianye.salon.service.AdminRoleService;
import com.tianye.salon.service.AdminUserService;
import com.tianye.salon.util.ConversionMd5;




@Controller
@RequestMapping("/admin-login")
public class AdminLoginController extends BaseController{
	//private static Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private AdminUserService adminUserService;
	@Autowired
	private AdminRoleService adminRoleService;
	@Autowired
	private AdminModuleService adminModuleService;
	
	@RequestMapping(value="login",method=RequestMethod.GET)
	public String login(Model model){
		model.addAttribute("userPo", new AdminUserForAuthDto());
		return "/admin/login";
	}
	
	/**
	 * 登录验证
	 * @throws Exception 
	 */
	@RequestMapping(value="loginvalidate")
	public String loginvalidate(@Valid @ModelAttribute(value="userPo") AdminUserForAuthDto userPo, BindingResult bindingResult, Model model, HttpSession session,HttpServletRequest request) throws Exception{
		if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            model.addAttribute("errStr", fieldError.getDefaultMessage());
            
            return "/admin/login";
        }

        // save product here

        //model.addAttribute("userPo", userPo);
		
		String errStr = "";
		
		String scode = (String)session.getAttribute("scode");
		System.out.println("scode is: "+scode);
		String context = request.getContextPath();
		
		if(scode!=null&&scode.equalsIgnoreCase(userPo.getScode())){
			System.out.println("userPo:"+userPo.toString());
			
			AdminUser user = adminUserService.selectByUsername(userPo.getUsername());
			if(null == user){
				errStr = "用户名/密码 错误！";
			} else {
				String passwordStr = ConversionMd5.toMd5(userPo.getPassword());
				System.out.println("passwordStr is:"+passwordStr+", user.getPwd is:"+user.getPwd());
				
				if(passwordStr.equals(user.getPwd())){
					session.setAttribute("adminuid", user.getId());
					session.setAttribute("adminusername", user.getUsername());
					
					AdminRole role = adminRoleService.selectRoleModuleByPrimaryKey(user.getRoleId());
					
					List<AdminModule> modules = new ArrayList<AdminModule>();
					if(null != role){
						modules = role.getModules();
					}
					Collections.sort(modules, new Comparator<AdminModule>() {

						@Override
						public int compare(AdminModule o1, AdminModule o2) {
							return o1.getPid0().compareTo(o2.getPid0());
						}
						
					});
					List<AdminModule> parent = new ArrayList<>();
					Integer pid = 0;
					AdminModule pAdminModule = null;
					Map<Integer, List<AdminModule>> children = new HashMap<>();//子菜单，key为父菜单id
					List<AdminModule> childs = new ArrayList<>();
					for(AdminModule module: modules){
						//父菜单
						if(module.getPid0() != pid){
							pid = module.getPid0();
							pAdminModule = adminModuleService.selectById(pid);
							if(!children.containsKey(module.getPid0())){
								parent.add(pAdminModule);
								childs = new ArrayList<>();
								children.put(module.getPid0(), childs);
							}
						}
						//子菜单
						if(!childs.contains(module)){
							childs.add(module);
						}
					}
					//父菜单排序
					Collections.sort(parent,new Comparator<AdminModule>() {
						@Override
						public int compare(AdminModule arg0, AdminModule arg1) {
							return arg0.getSortNum().compareTo(arg1.getSortNum());
						}
					});
					
					StringBuffer sb = new StringBuffer();
					List<Integer> mids = new ArrayList<Integer>();
					List<String> link = new ArrayList<String>();//@Description 存放该用户可访问的所有连接地址@author sushile
					link.add("index");
					for(AdminModule module : parent){
							if(sb.length() != 0){
								sb.append("</ul></li>");
							}
							sb.append("<li ><a href=\"#\"><img src=\"/views/images/icons/menu/dark/layout.png\" alt=\"\" /> "+module.getName()+"</a><ul>");
							//加载线面子菜单
							if(null != children && !children.isEmpty() && null != children.get(module.getId())){
								List<AdminModule> adminModules = children.get(module.getId());
								//子菜单排序
								Collections.sort(adminModules,new Comparator<AdminModule>() {
									@Override
									public int compare(AdminModule arg0, AdminModule arg1) {
										return arg0.getSortNum().compareTo(arg1.getSortNum());
									}
								});
								for(AdminModule child : adminModules){
									link.add(child.getLink());
									sb.append("<li ><a id=\"menu_"+child.getLink()+"\" href=\"/"+child.getLink()+"/index\">"+child.getName()+"</a></li>");
									mids.add(child.getId());
								}
							}
					}
					sb.append("</ul></li>");
					
					//System.out.println(sb.toString());
					
					
					
					session.setAttribute("left_menu", sb.toString());
					session.setAttribute("rid", role.getId());
					session.setAttribute("mids", mids);
					
					return "redirect:/admin/index";
				} else {
					errStr = "用户名/密码 错误！";
				}
			}
			
		} else {
			errStr = "验证码错误！";
		}
		
		model.addAttribute("errStr", errStr);
		
		return "/admin/login";
	}

	@RequestMapping(value="logout")
	public void logout(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap, HttpSession session) throws ServletException, IOException{
		
		session.removeAttribute("adminuid");
		session.removeAttribute("oldurl");
		session.removeAttribute("adminusername");
		session.removeAttribute("left_menu");
		session.removeAttribute("rid");
		session.removeAttribute("mids");
		
		request.getRequestDispatcher("/admin-login/login").forward(request, response);
	}
}


